import { createContext, useState, useContext } from "react";

// This context is used to manage the state of the menus in the application

// It provides a way to share the menus state and the function to update it across the component tree

// 用 React Context 管理菜单和动态路由

export const MenuContext = createContext();
export const useMenu = () => useContext(MenuContext);

export function MenuProvider({ children }) {
  const [menus, setMenus] = useState(()=>{
    const localMenus = localStorage.getItem("menus");
    return localMenus ? JSON.parse(localMenus) : [];
  });
  // 初始化菜单状态，从 localStorage 中读取
  // 如果 localStorage 中没有菜单，则默认为空数组
  // 这样可以确保在应用加载时就有初始菜单状态
  // 并且可以在其他组件中通过 useMenu 获取和更新菜单状态

  // 当 setMenus 更新时同步到 localStorage
  const setMenusAndPersist = (data) => {
    setMenus(data);
    localStorage.setItem("menus", JSON.stringify(data));
  };


  return (
    <MenuContext.Provider value={{ menus, setMenus: setMenusAndPersist }}>
      {children}
    </MenuContext.Provider>
  );
}

